package com.gobang.demo.game;

import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

@Component
// 房间管理器
// 用来管理匹配成功的用户进入到的游戏房间
public class RoomManager {
    private ConcurrentHashMap<String,Room> rooms = new ConcurrentHashMap<>();
    private ConcurrentHashMap<Integer,String> userIdToRoomid = new ConcurrentHashMap<>();

    // 将匹配到的游戏玩家加入到同一房间
    public void add(Room room,int userid1,int userid2) {
        rooms.put(room.getRoomId(),room);
        userIdToRoomid.put(userid1,room.getRoomId());
        userIdToRoomid.put(userid2,room.getRoomId());
    }
    // 将游戏玩家移除出房间
    public void remove(Room room,int userid1,int userid2) {
        rooms.remove(room.getRoomId());
        userIdToRoomid.remove(userid1);
        userIdToRoomid.remove(userid2);

    }
    public Room getRoomByRoomId(String roomId) {
        return rooms.get(roomId);
    }
    public Room getRoomByUserId (Integer userId) {
        String roomId = userIdToRoomid.get(userId);
        if (roomId == null) {
            return null;
        }
        return getRoomByRoomId(roomId);
    }
}
